package com.sinopec.android.net;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.MultipartPostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.sinopec.android.util.LogUtil;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;


/**
 * 【http请求类】
 * @ClassName:HttpManager
 * @Description:TODO
 * @author liuwei
 * @date 2012-3-8上午10:12:26
 *
 */
@SuppressWarnings("deprecation")
public class HttpManager {
	public static DefaultHttpClient httpclient;
	private static final int timeoutConnection = 3000;  //连接超时
	private static final int timeoutSocket = 10000; //
	//静态初始化 httpclient
	static {
		if(httpclient == null){
			HttpParams httpParameters = new BasicHttpParams();
			// Set the timeout in milliseconds until a connection is established. 
			HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
			// in milliseconds which is the timeout for waiting for data.  
		    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); 
		    httpclient = new DefaultHttpClient(httpParameters);
		}
	} 
	
	/**
	 * 【httpget请求类】
	 * @Title :doGet
	 * @Description :TODO
	 * @params @param reqUrl
	 * @params @return
	 * @return String
	 * @throws
	 * 
	 */
	public static String  doGet(String reqUrl){
		try{
			HttpGet httpGet = new HttpGet(reqUrl);
			LogUtil.printInfo("request :"+reqUrl);
			HttpResponse response = null;
			if(ThreadManger.isGo){
				response= httpclient.execute( httpGet );  
				int status = response.getStatusLine().getStatusCode();  
				if ( status != HttpStatus.SC_OK )  
					throw new Exception( "" );  
				return EntityUtils.toString( response.getEntity(), HTTP.UTF_8 ); 
			}else{
				return null;
			}
		}catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	/**
	 * 【http post请求】
	 * @Title :doPost
	 * @Description :TODO
	 * @params @param reqUrl
	 * @params @param hashMap
	 * @params @return
	 * @return String
	 * @throws
	 * 
	 */
	public static String doPost(String reqUrl, HashMap<String, String> hashMap) {
			ArrayList<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
			String result = null;
			HttpPost httppost = null;
			InputStream content = null;
			try {
				httppost = new HttpPost(reqUrl);
				LogUtil.printInfo("request :"+reqUrl);
			
			if (hashMap != null) {
				Set<String> keys = hashMap.keySet();
				for (Iterator<String> i = keys.iterator(); i.hasNext();) {
					String key = (String) i.next();
					String value = (String) hashMap.get(key);
					if(key == null || key.trim().length()==0 || value == null || value.trim().length()==0){
						continue;
					}
					LogUtil.printInfo(key +" : "+value);
					pairs.add(new BasicNameValuePair(key, value));
				}
			}
			
			int responseCode=0;
			
				UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(pairs,	HTTP.UTF_8);
				
				/** 将POST数据放入http请求 */
				httppost.setEntity(p_entity);
				
				/** 发出实际的HTTP POST请求 */
				HttpResponse response = null;
				if(ThreadManger.isGo){
					LogUtil.printInfo("post 之前:");
					response = httpclient.execute(httppost);
					LogUtil.printInfo("post 之后:");
					responseCode=response.getStatusLine().getStatusCode();
					if(responseCode == HttpStatus.SC_OK){
						HttpEntity entity = response.getEntity();
						content = entity.getContent();
						result = convertStreamToString(content);
					}else{
						return null;
					}
				}else{
					return null;
				}
				
				
			} catch (Exception uee) {
				uee.printStackTrace();
				return null;
			} finally{
				try {
					if(httppost!=null){
						httppost.abort();
					}
					if(content!=null)
					{
						content.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
					return null;
				}
			}
			LogUtil.printInfo(result);
			return result;
		}
		
		/**
		 * 【上传文件请求类】
		 * @Title :uploadFile
		 * @Description :TODO
		 * @params @param reqUrl
		 * @params @param hashMap
		 * @params @return
		 * @return String
		 * @throws
		 * 
		 */
		public static String uploadFile(String reqUrl, HashMap hashMap) {
			
			MultipartPostMethod multMethod  = new MultipartPostMethod(reqUrl);
			
			LogUtil.printInfo("request :"+reqUrl);
			InputStream content = null;
			String result = null;
			
			if (hashMap != null) {
				Set<String> keys = hashMap.keySet();
				for (Iterator<String> i = keys.iterator(); i.hasNext();) {
					String key = (String) i.next();
					if(key.equals("img")){
						File file = (File) hashMap.get(key);
						FilePart filePart=null;
						if(file!=null){
							try {
								filePart = new FilePart("img",file);
								filePart.setContentType("image/jpeg");
							} catch (FileNotFoundException e) {
								e.printStackTrace();
							}
							LogUtil.printInfo("file.length : "+file.length());
							multMethod.addPart(filePart);
						}
					}else{
						String value = (String) hashMap.get(key);
						if(key == null || key.trim().length()==0 || value == null || value.trim().length()==0){
							continue;
						}
						LogUtil.printInfo(key +" : "+value);
						StringPart stringPart = new StringPart(key, value);
						stringPart.setCharSet("UTF-8");//设置提交文字编码
						multMethod.addPart(stringPart);
					}
				}
			}
			
			int responseCode=0;
			try {
				
				HttpClient client = new HttpClient();
				/** 发出实际的HTTP POST请求 */
				int httpStatusCode= client.executeMethod(multMethod);
				if(httpStatusCode==HttpStatus.SC_OK){
					result = multMethod.getResponseBodyAsString();
				}
				
			} catch (Exception uee) {
				uee.printStackTrace();
				return null;
			}finally{
				try{
					if(content!=null)
					{
						content.close();
					}
				}catch (IOException e) {
					e.printStackTrace();
					return null;
				}
				//释放连接
				multMethod.releaseConnection();
			}
			if(!"".equals(result)&&result!=null){
				LogUtil.printInfo(result);
			}
			return result;
		}
		
		/**
		 * 【将流转换成字符串】
		 * @Title :convertStreamToString
		 * @Description :TODO
		 * @params @param is
		 * @params @return
		 * @return String
		 * @throws
		 * 
		 */
		public static String convertStreamToString(InputStream is) {
			BufferedReader reader = new BufferedReader(new InputStreamReader(is));
			StringBuilder sb = new StringBuilder();
	
			String line = null;
			try {
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return sb.toString();
		}
	
		/**
		 * 检查网络状态
		 * @author huangyu
		 *
		 */
			public static boolean checkNetWork(Context context){
				//判断网络是否可用，如果不可用，给出提示
		        boolean isAvailable = netWorkIsAvailable(context);
		        if(!isAvailable){//如果不可用
		       	 openDialog(context);
		       	 return false;
		        }
		        return true;
			}
			
			/**
			 * 判断网络是否可用
			 * @Title :netWorkIsAvailable
			 * @Description :TODO
			 * @params @param context
			 * @params @return
			 * @return boolean
			 * @throws
			 * 
			 */
			public static boolean netWorkIsAvailable(Context context) {
				ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE ); 
				NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
				if(activeNetInfo!=null){
					if(activeNetInfo.isAvailable()){
						return true;
					}else{
						return false;
					}
				}
				return false;
			}
			
			/**
			 * 弹出网络不可用提示框
			 * @Title :openDialog
			 * @Description :TODO
			 * @params @param context
			 * @return void
			 * @throws
			 * 
			 */
			private static void openDialog(final Context context) {
				final Builder builder=new AlertDialog.Builder(context);
				builder.setTitle("没有可用的网络");
		        builder.setMessage("请开启GPRS或WIFI网络连接");
		        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int whichButton) {
		            	   Intent mIntent = new Intent("/");
		                   ComponentName comp = new ComponentName("com.android.settings", "com.android.settings.WirelessSettings");
		                   mIntent.setComponent(comp);
		                   mIntent.setAction("android.intent.action.VIEW");
		                   context.startActivity(mIntent);
	
			}
		        }).setNeutralButton("取消", new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int whichButton) {
		                dialog.cancel();
		            }
		        }).create().show();
	
		}
}

